<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax例子</title>
</head>
<body>
<div id="example"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<!--<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>-->
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
<script type="text/babel">/*告诉babel.js解析里面的jsx的代码*/

class UserGist extends React.Component {
    constructor(props) {
        super(props);
        this.state = {username: '', lastGistUrl: ''};
    }


    componentDidMount() {

        //JQuery 的方式
        /*this.serverRequest = $.get(this.props.source, function (result) {
            var lastGist = result[0];
            this.setState({
                username: lastGist.owner.login,
                lastGistUrl: lastGist.html_url
            });
        }.bind(this));*/
        console.log("componentDidMount begin ... ")


        //axios方式
        axios.get(this.props.source)
            .then(response => {
                const result = response.data;
                console.log(result)
                var lastGist = result[0];
                this.setState({
                    username: lastGist.owner.login,
                    lastGistUrl: lastGist.html_url
                })
            })
            .catch(function (error) {
                console.log(error)
            })


        //fetch方式
        /*fetch(this.props.source, {method: "GET"})
            .then(response => response.json())
            .then(data => {
                console.log(data)
                if(data.message) {
                    alert(`请求失败: ${data.message}`)
                } else {
                    const lastGist = data[0]
                    this.setState({
                        username: lastGist.owner.login,
                        lastGistUrl: lastGist.html_url
                    })
                }
            })*/

        console.log("componentDidMount end ... ")
    }

    componentWillUnmount() {
        this.serverRequest.abort();
    }

    render() {
        const {username,lastGistUrl} = this.state;
        if(!username){
            return <h2>loading...</h2>;
        }else {
            return (
                    <div>
                        {this.state.username} 用户最新的 Gist 共享地址：
                        <a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
                    </div>
            );
        }

    }
}

ReactDOM.render(
        <UserGist source="https://api.github.com/users/octocat/gists" />,
    document.getElementById('example')
);

</script>
</body>
</html>